package cn.op.portal.filter;

import java.io.IOException;
import java.net.URLDecoder;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletRequestWrapper;
import javax.servlet.http.HttpServletResponse;

public class CharacterEncodingFilter implements Filter {

	private String charset;
	private String defaultCharset = "utf-8";
	
	@Override
	public void init(FilterConfig filterConfig) throws ServletException {
		charset = filterConfig.getInitParameter("charset");
		if(null==charset) {
			charset = defaultCharset;
		}
	}

	@Override
	public void doFilter(ServletRequest req, ServletResponse resp,
			FilterChain chain) throws IOException, ServletException {
		HttpServletRequest request = (HttpServletRequest) req;
		HttpServletResponse response = (HttpServletResponse) resp;
		
		request.setCharacterEncoding(charset);
		response.setContentType("text/html;charset=" + charset);
		chain.doFilter(new EncodingRequest(request), response);
	}
	
	@Override
	public void destroy() {
		// TODO Auto-generated method stub

	}
	
	class EncodingRequest extends HttpServletRequestWrapper{
		private HttpServletRequest request;
		
		public EncodingRequest(HttpServletRequest request) {
			super(request);
			this.request = request;
		}

		@Override
		public String getParameter(String name) {
			String value = request.getParameter(name);
			if(null==value) {
				return null;
			}
			if("post".equalsIgnoreCase(request.getMethod())) {
				return value;
			}
			try {
				value = new String(value.getBytes("iso8859-1"),charset);
				return value;
			} catch (Exception e) {
				throw new RuntimeException(e);
			}
		}
	}
}
